// components/wx-phone/wx-phone.js
const app = getApp();
import * as API_Passport from '../../api/passport'

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    hideAuth: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    uuid: '',
    isHidden: false
  },

  lifetimes: {
    attached: function () {
      // 在组件实例进入页面节点树时执行
      const uuid = wx.getStorageSync('uuid');
      this.setData({
        uuid: uuid,
        isHidden: this.properties.hideAuth
      })
    }
  },
  observers:{
    hideAuth(newVal) {
      this.setData({
        isHidden: newVal
      })
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
       * @date 2020/05/18
       * @author wolfMan
       * @description {关闭手机号授权弹层}}
     */
    closePhone() {
      const _pages = getCurrentPages();
      const _currentPage = _pages[_pages.length - 1];
      if (_currentPage.route === 'pages/auth/login/login') {
        wx.navigateBack();
      } else {
        this.setData({
          isHidden: true
        });
      };
    },
    /**
       * @date 2020/05/18
       * @author wolfMan
       * @description {手机号授权}}
     */
    getPhoneNumber(e) {
      const _detail = e.detail;
      if (_detail.errMsg === 'getPhoneNumber:ok') {
        const _iv = _detail.iv;
        const _telObj = _detail.encryptedData;
        wx.login({
          success: res => {
            const _code  = res.code;
            let _params = {
              uuid: this.data.uuid,
              code: _code,
              encrypted_data: _telObj,
              iv: _iv
            };
            API_Passport.decryptWechat(_params).then(response => {
              app.globalData.phone = response.purePhoneNumber;
              wx.setStorageSync('phone', response.purePhoneNumber);
              this.mobileLogin();
              this.closePhone();
            })
          }
        });
      } else {
        console.log('拒绝手机号授权！');
      }
    },
    /**
       * @date 2020/05/18
       * @author wolfMan
       * @description {手机号登录}}
     */
    async mobileLogin() {
      // 检测是否登录 如果已经登录 或者登录结果为账户未发现 则不再进行自动登录
      if (wx.getStorageSync('refresh_token')) return
      try {
        const { uuid, phone, openid, unionid } = app.globalData;
        let _params = {
          uuid: uuid,
          mobile: phone,
          openid: openid,
          unionid: unionid,
          nickname: wx.getStorageSync('nickName')
        };
        let result = await API_Passport.mobileLogin(_params);
        app.afterLoginInfo(result);
      } catch (e) {
        console.log("错误信息", e);
      }
    }
  }
})
